package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;

import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.dto.ChatMessage.GetAllChatValueDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.websocket.RedisChatSnapshot;
import com.tbvtc.agriculturalcreditchainserver2025.login.LoginUser;
import com.tbvtc.agriculturalcreditchainserver2025.login.LoginUserHolder;
import com.tbvtc.agriculturalcreditchainserver2025.service.IChatMessageService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import com.tbvtc.agriculturalcreditchainserver2025.utils.voice.VoiceFileUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/admin/chat")
@Tag(name = "聊天对话接口")
public class ChatController {
    @Resource(name = "TredisTemplate")
    private RedisTemplate<String, RedisChatSnapshot> redisTemplate;
    @Resource
    private IChatMessageService chatMessageService;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    private VoiceFileUtil voiceFileUtil;

    @GetMapping
    @Operation(summary = "获取聊天最新记录")
    public Result getLatestChat() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        List<RedisChatSnapshot> list = new ArrayList<>();
        Map<Object, Object> allSnapshots = redisTemplate.opsForHash().entries(RedisConstant.CHAT_SNAPSHOT_KEY_PREFIX + loginUser.getUserId());
        for (Map.Entry<Object, Object> entry : allSnapshots.entrySet()) {
            //拿到所有的集合
            RedisChatSnapshot snapshot = (RedisChatSnapshot) entry.getValue();
            String unreadCount = stringRedisTemplate.opsForValue().get(RedisConstant.CHAT_MESSAGE_COUNT_KEY + loginUser.getUserId() + ":" + snapshot.getSenderId());
            snapshot.setUnreadCount(unreadCount == null ? 0 : Integer.parseInt(unreadCount));
            list.add(snapshot);
        }
        return RUtils.success(list);
    }

    @PostMapping("/allChatValue")
    @Operation(summary = "根据senderId获取所有聊天记录")
    public Result getAllChatValue(@RequestBody GetAllChatValueDto getAllChatValueDto) {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        getAllChatValueDto.setReceiverId(loginUser.getUserId());
        stringRedisTemplate.opsForValue().set(RedisConstant.CHAT_MESSAGE_COUNT_KEY + loginUser.getUserId() + ":" + getAllChatValueDto.getSenderId(), String.valueOf(0));
        return chatMessageService.getAllChatValue(getAllChatValueDto);
    }

    @Operation(summary = "上传音频文件返回访问地址")
    @PostMapping("/uploadAudioFile")
    public Result uploadAudioFile(@RequestParam("file") MultipartFile file) {
        String base64 = null;
        try {
            base64 = Base64.getEncoder().encodeToString(file.getBytes());
            String uuid = UUID.randomUUID().toString();
            String url = voiceFileUtil.saveBase64AsWav(base64, uuid);
            return RUtils.success(url);
        } catch (IOException e) {
            log.info("上传音频文件失败");
        }
        return RUtils.Err(0, "上传音频文件失败");
    }
}
